<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="dialogData.show"
               center
               @close="$emit('closedialog')"
               width="65%">
      <el-form :model="form"
               :rules="formRules"
               ref="formRef"
               label-position="right"
               label-width="120px">
        <el-form-item label="试纸名称：">
          <el-input placeholder="请输入"
                    v-model="model.testStripName"
                    disabled
                    style="width:26%"></el-input>
        </el-form-item>
        <el-form-item label="生产厂商：">
          <el-select @change="handleManufacturer"
                     v-model="model.factoryId"
                     disabled
                     placeholder="请选择厂商">
            <el-option v-for="item in factoryList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产许可证：">
          <el-select v-model="model.productionLicenseId"
                     placeholder="请选择生产许可证"
                     disabled
                     @change="handleProductLicensePage">
            <el-option v-for="item in licenseList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册证：">
          <el-select v-model="model.medicalDeviceCertificateId"
                     placeholder="请选择医疗器械证"
                     disabled>
            <el-option v-for="item in certificateList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试纸类型："
                      prop="testStripTypeId">
          <el-select v-model="model.testStripTypeId"
                     placeholder="请选试纸类型"
                     @change="handleTestStripType">
            <el-option v-for="item in paperTypeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="检测项目："
                      prop="deviceId">
          <el-select v-model="model.deviceId"
                     placeholder="请选择检测项目"
                     clearable
                     filterable
                     :disabled="!model.testStripTypeId"
                     @change="handleDevice">
            <el-option v-for="item in checkItemList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <!-- 定性试纸 -->
        <template v-if="model.testStripTypeId === 4">
          <el-form-item>
            <el-radio-group v-model="currTitleType"
                            @change="changeRadioTitle">
              <el-radio-button v-for="item in currTitleList"
                               :label="item.type"
                               :key="item.type">{{ item.name }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <!-- 定性试纸-使用方式 -->
          <template v-if="currTitleType === 1">
            <el-form-item label="描述：">
              <el-input type="textarea"
                        placeholder="请输入描述"
                        v-model="model.useDesc"></el-input>
            </el-form-item>
            <el-form-item label="图片：">
              <el-upload class="avatar-uploader"
                         :action="imageUploadUrl"
                         :file-list="fileListImg"
                         accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                         :on-success="onSuccess"
                         :before-upload="beforeAvatarUpload"
                         :on-remove="(file, fileList) => handleRemove(file, fileList, currTitleType)"
                         list-type="picture-card">
                <el-button size="small"
                           type="primary">点击上传
                </el-button>

              </el-upload>
            </el-form-item>
          </template>
          <!-- 定性试纸-结果判读 -->
          <template v-if="currTitleType === 2">
            <el-form-item label="图片：">
              <el-upload class="avatar-uploader"
                         :action="imageResultsUploadUrl"
                         :file-list="fileListResultImg"
                         accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                         :on-success="onSuccessResults"
                         :on-remove="(file, fileList) => handleRemove(file, fileList, currTitleType)"
                         :before-upload="beforeAvatarUpload"
                         list-type="picture-card">
                <el-button size="small"
                           type="primary">点击上传
                </el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="结果释义：">
              <el-button type="primary"
                         @click="handleAdd(resultParaphraseTableData, 1)">增 加
              </el-button>
              <el-table :data="resultParaphraseTableData"
                        border
                        class="mt-20">
                <el-table-column label="结果">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.result"
                              class="w-200"
                              placeholder="请输入结果"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="释义">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.content"
                              class="w-200"
                              placeholder="请输入释义"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="danger"
                               @click="handleDel(resultParaphraseTableData, scope.$index)">删 除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </template>
          <!-- 定性试纸-使用方式 -->
          <template v-if="currTitleType === 3">
            <el-form-item label="注意事项：">
              <el-input type="textarea"
                        placeholder="请输入注意事项"
                        v-model="model.notes"></el-input>
            </el-form-item>
            <el-form-item label="结果：">
              <el-button type="primary"
                         @click="handleAdd(resultTableData, 2)">增 加
              </el-button>
              <el-table :data="resultTableData"
                        border
                        class="mt-20">
                <el-table-column label="结果">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.result"
                              class="w-200"
                              placeholder="请输入结果"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="danger"
                               @click="handleDel(resultTableData, scope.$index)">删 除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </template>
        </template>
        <!-- 光化学、电化学、第三方试纸、胶体金 -->
        <template v-else>
          <el-form-item>
            <el-radio-group v-model="model.goodsTypeIds"
                            @change="changeRadio">
              <el-radio-button v-for="list in listData"
                               :label="list.goodsTypeIds"
                               :value="list.goodsTypeIds"
                               :key="list.goodsTypeIds">
                {{ list.goodsName }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <!-- 自有设备 -->
          <div v-if="currProperty === 1">
            <el-form-item label="数据读取方式：">
              <el-radio-group v-model="model.dataReadWay">
                <el-radio :label="1">手动录入</el-radio>
                <el-radio :label="2"
                          v-if="model.testStripTypeId !== 4">设备读取
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="反应时间：">
              <el-select placeholder="请选择反应时间单位"
                         v-model="model.responseTimeUnit"
                         @change="handleChangeTimeUnit1">
                <el-option v-for="item in timeUnitList1"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model="model.responseTime"
                         placeholder="请选择反应时间">
                <el-option v-for="num in reactionTimeList"
                           :key="num-1"
                           :label="num-1"
                           :value="num-1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="有效检测时间：">
              <el-select v-model="model.checkTimeUnit"
                         @change="handleChangeTimeUnit2"
                         placeholder="请选择有效检测时间单位">
                <el-option v-for="item in timeUnitList2"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
              <el-select v-model="model.checkTime"
                         placeholder="请选择有效检测时间">
                <el-option v-for="num in detectionTimeList"
                           :key="num-1"
                           :label="num-1"
                           :value="num-1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="有效检测温度：">
              <el-input placeholder="请输入检测温度最小值"
                        v-model="model.checkTemperatureMin"
                        style="width:25.5%"></el-input>
              <el-input placeholder="检测温度最大值"
                        v-model="model.checkTemperatureMax"
                        style="width:25.5%"></el-input>
              <span>℃</span>
            </el-form-item>
          </div>
          <!-- 第三方设备 -->
          <div v-if="currProperty === 2">
            <el-form-item label="检测项code：">
              <el-input placeholder="请输入检测项code"
                        v-model="model.deviceCode"
                        class="w-200"></el-input>
            </el-form-item>
          </div>
        </template>
        <!-- 添加动态指标 -->
        <div>
          <el-button type="primary"
                     :disabled="!model.deviceId"
                     @click="handleAdd(null, 3)">添 加
          </el-button>
          <el-table border
                    :data="model.deviceReferenceDtoList"
                    class="mt-20">
            <el-table-column label="指标">
              <template slot-scope="scope">
                <el-select v-model="scope.row.referenceId"
                           placeholder="请选择指标"
                           clearable
                           @change="val=>chagneReference(val, scope.$index)">
                  <el-option v-for="item in testPaperList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="单位">
              <template slot-scope="scope">
                <el-input v-model="scope.row.referenceUnit"
                          class="w-200"
                          clearable
                          placeholder="请输入单位"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="指标code">
              <template slot-scope="scope">
                <span v-if="model.testStripTypeId === 4">
                  <el-input v-model="scope.row.code"
                            class="w-200"
                            :disabled="true"
                            clearable
                            placeholder="请输入指标code"></el-input>
                </span>
                <span v-else>
                  <label v-if="currProperty === 1">
                    <el-input v-model="scope.row.code"
                              class="w-200"
                              :disabled="true"
                              clearable
                              placeholder="请输入指标code"></el-input>
                  </label>
                  <label v-if="currProperty === 2">
                    <el-input v-model="scope.row.referenceCode"
                              class="w-200"
                              clearable
                              placeholder="请输入指标code"></el-input>
                  </label>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="criterion"
                             label="判断标准"
                             width="150">
              <template slot-scope="scope">
                <el-tag size="medium"
                        style="cursor: pointer"
                        @click="openConfig(scope.row, scope.$index)">配置判断标准
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sortNum"
                             label="排序">
              <template slot-scope="scope">
                <el-input clear="w-200"
                          v-model="scope.row.sortNum"
                          clearable
                          placeholder="请输入排序"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作"
                             width="100">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="danger"
                           @click="handleDelete(model.deviceReferenceDtoList, scope.$index)">删 除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <div slot="footer"
           class="dialog-footer">
        <el-button @click="$emit('closedialog')">返 回</el-button>
        <el-button type="success"
                   @click="submitForm"
                   :disabled="model.deviceReferenceDtoList.length < 1">确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 配置判断标准弹窗 S -->
    <el-dialog :visible.sync="isConfigView"
               title="配置指标判断标准"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="70%">
      <el-button type="success"
                 @click="addConfig(dataList)">新 增
      </el-button>
      <div v-for="(item, index) in dataList"
           :key="index"
           class="mt-20">
        <el-card>
          <el-form :inline="true"
                   :model="item">
            <el-form-item label="样本"
                          prop="sampleName">
              <el-select v-model="item.sampleName"
                         multiple
                         class="w-200">
                <el-option v-for="item in sampleList"
                           :key="item.id"
                           :value="item.name"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结果"
                          prop="result">
              <el-input v-model="item.result"
                        placeholder="判断结果"
                        style="width: 100px"
                        clearable></el-input>
            </el-form-item>
            <el-form-item label="范围"
                          prop="leftValue">
              <el-input v-model="item.leftValue"
                        placeholder="最小值"
                        style="width: 100px"
                        clearable></el-input>
            </el-form-item>
            <el-form-item prop="leftRelation">
              <el-select v-model="item.leftRelation"
                         placeholder="关系"
                         style="width: 120px"
                         clearable>
                <el-option v-for="relation in relations_1"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检测值"
                          prop="rightRelation">

              <el-select v-model="item.rightRelation"
                         placeholder="关系"
                         style="width: 120px"
                         clearable>
                <el-option v-for="relation in relations_2"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="rightValue">
              <el-input v-model="item.rightValue"
                        placeholder="最大值"
                        style="width: 100px"
                        clearable></el-input>
            </el-form-item>
            <el-button type="warning"
                       @click="removeConfig(dataList, index)">移 除
            </el-button>
            <br/>
            <el-form-item label="条件"
                          prop="type">
              <el-select v-model="item.type"
                         placeholder="请选择条件"
                         style="width: 120px"
                         clearable
                         @change="(value)=>{changeValueList(value, index)}">
                <el-option v-for="relation in typeList"
                           :key="relation.value"
                           :label="relation.label"
                           :value="relation.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 性别 -->
            <template v-if="item.isShowSelect">
              <el-form-item prop="typeValue">
                <el-select v-model="item.typeValue"
                           placeholder="请选择关系"
                           clearable
                           style="width: 150px">
                  <el-option v-for="relation in item.valueListSex"
                             :key="relation.value"
                             :label="relation.label"
                             :value="relation.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
            <!-- 血糖 -->
            <template v-if="item.isShowSelect2">
              <el-form-item prop="typeValue">
                <el-select v-model="item.typeValue"
                           placeholder="请选择关系"
                           clearable
                           style="width: 150px">
                  <el-option v-for="relation in item.valueListBloodSugar"
                             :key="relation.value"
                             :label="relation.label"
                             :value="relation.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
            <!-- 年龄 -->
            <template v-if="item.isShowInput">
              <el-form-item prop="age">
                <el-input-number v-model="item.age"
                                 :step="1"
                                 :min="1"
                                 step-strictly></el-input-number>
              </el-form-item>
            </template>


            <!-- 结论 -->
            <template>
              <el-form-item>
                <el-select v-model="item.status"
                           placeholder="请选择状态"
                           clearable
                           style="width: 120px">
                  <el-option v-for="relation in stateDataSource"
                             :key="relation.status"
                             :label="relation.name"
                             :value="relation.status">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>

            <div class="row-item">
              <el-form-item label="提示"
                            prop="note">
                <el-input v-model="item.note"
                          style="width:100%;"
                          type="textarea"
                          placeholder="请输入提示">
                </el-input>
              </el-form-item>
              <el-form-item label="参考范围"
                            prop="referenceRange">
                <el-input v-model="item.referenceRange"
                          type="textarea"
                          style="width:100%;"
                          placeholder="请输入参考范围"></el-input>
              </el-form-item>
            </div>
          </el-form>
        </el-card>
      </div>
      <div class="operationView mt-20">
        <el-button @click="isConfigView = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveItem(dataList, currIndex)">保 存
        </el-button>
      </div>
    </el-dialog>
    <!-- 配置判断标准弹窗 E -->
  </div>
</template>

<script>
export default {
  props: ['dialogData'],
  data() {
    return {
      form: {},
      title: '',
      checkItemList: [], // 检测项目
      paperTypeList: [], // 试纸类型
      factoryList: [], // 生产厂商
      licenseList: [], // 生产许可证
      certificateList: [], // 医疗器械证
      timeUnitList1: [ // 时间单位
        {
          value: 1,
          label: 's'
        },
        {
          value: 2,
          label: 'min'
        },
        {
          value: 3,
          label: 'h'
        }],
      timeUnitList2: [ // 时间单位
        {
          value: 1,
          label: 's'
        },
        {
          value: 2,
          label: 'min'
        },
        {
          value: 3,
          label: 'h'
        }],
      reactionTimeList: null,
      detectionTimeList: null,
      checkTime_second: null, // 检测时间秒
      tempGoodsTypeIds: [], // 检测设备
      productLicenseId: '', // 生产许可证ID
      medicalDeviceCertificateId: '', // 注册证ID
      model: {
        id: '', // 试纸厂商ID
        testStripId: '', // 试纸ID
        factoryId: '', // 厂商ID
        testStripTypeId: '', // 试纸类型, 1.电化学,2.干化学,3.荧光/胶体金,4.定性试纸
        deviceId: null, // 检测项目ID
        responseTime: '', // 反应时间
        checkTime: '', // 有效检测时间
        responseTimeUnit: '', // 反应时间单位
        checkTimeUnit: '', // 有效检测时间单位
        checkTemperatureMin: 0, // 检测温度最小值
        checkTemperatureMax: 99, // 检测温度最大值
        checkTemperatureUnit: 1, // 检测温度单位（1:℃）
        dataReadWay: 1, // 数据读取方式（1 手动输入 2 设备读取）
        efficacy: 1, // 试纸功效（1 定量 2定性）
        productionLicenseId: '', // 生产许可证ID
        medicalDeviceCertificateId: '', // 注册证ID

        useDesc: '', // 使用描述
        useImageUrl: '', // 使用图片
        resultImageUrl: '', // 结果判读图片
        resultParaphrase: '', // 结果释义
        notes: '', // 注意事项
        results: '', // 结果
        goodsTypeIds: '', // 检测设备ID字符串
        property: '', // 1 自有设备 2 三方设备
        deviceName: '', // 第三方设备-检测项名称
        deviceCode: '', // 第三方设备-检测项目code
        deviceThirdMappingId: null, // 第三方设备 - 三方设备检测信息ID
        deviceReferenceDtoList: [
          {
            id: null, // 检测项与检测指标关系ID
            testStripFactoryId: '', // 试纸厂商ID
            code: '', // 检测指标code
            deviceId: '', // 检测项目ID
            referenceId: '', // 指标ID
            referenceUnit: '', // 检测指标单位
            sortNum: 1, // 排序
            criterion: '', // 判断结果字符串
            criterionList: []
          }
        ]
      },
      currTitleType: 1, // 定性试纸 类型
      currProperty: 1, // 自有设备、第三方设备
      currTitleList: [
        {type: 1, name: '使用方式'},
        {type: 2, name: '结果判读'},
        {type: 3, name: '手动输入结果'}
      ],
      stateDataSource: [
        {
          status: 0,
          name: '异常'
        },
        {
          status: 1,
          name: '正常'
        }
      ],
      imageUploadUrl: this.api.appUpgradeUpload.url, // 定性试纸-使用方式
      imageResultsUploadUrl: this.api.appUpgradeUpload.url, // 定性试纸-结果判读
      resultParaphraseTableData: [ // 定性试纸-结果判读-结果释义
        {'result': '', 'content': ''}
      ],
      resultTableData: [ // 定性试纸-手动输入结果-结果
        {result: ''}
      ],
      formRules: {},
      sampleList: [], // 样本列表
      isConfigView: false,
      innerVisible: false,
      strSampleName: '',
      testPaperList: [], // 试纸指标
      testStripSampleList: [], // 试纸指标

      relations_1: [
        {
          value: '<',
          label: '大于'
        },
        {
          value: '<=',
          label: '大于等于'
        }
      ],
      relations_2: [
        {
          value: '<',
          label: '小于'
        },
        {
          value: '<=',
          label: '小于等于'
        },
        {
          value: '=',
          label: '等于'
        },
      ],
      typeList: [
        {
          value: 'sex',
          label: '性别'
        },
        {
          value: 'age',
          label: '年龄'
        },
        {
          value: 'bloodSugar',
          label: '血糖'
        }
      ],
      valueListSex: [],
      currIndex: 0,
      listData: [], // 设备列表标题
      deviceGoodsTypeDtos: [],
      resultImageUrlArray: [],
      fileListImg: [],
      fileListResultImg: [],
      dataList: [], // 每一行里面的criterionList 数据
    }
  },
  methods: {
    // 定性试纸-使用方式 上传图片类型
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    // 定性试纸-使用方式 上传图片成功
    onSuccess(res) {
      if (res.code === '200') {
        this.$message.success('上传成功!');
        // this.model.useImageUrl = JSON.stringify(res.object);
        let temp = [];
        res.object.forEach((item, v) => {
          temp.push({
            name: v,
            url: item
          })
        });
        this.fileListImg = [...temp, ...this.fileListImg];
      }
    },
    // 移除图片
    handleRemove(file, fileList, currTitleType) {
      if (currTitleType === 1) {
        let key = 0, url = file.url;
        this.fileListImg.forEach((item, index) => {
          if (item.url === url) {
            key = index;
          }
        });
        this.fileListImg.splice(key, 1);
      }
      if (currTitleType === 2) {
        let key = 0, url = file.url;
        this.fileListResultImg.forEach((item, index) => {
          if (item.url === url) {
            key = index;
          }
        });
        this.fileListResultImg.splice(key, 1);
      }

    },

    // 定性试纸-结果判读 上传图片成功
    onSuccessResults(res) {
      if (res.code === '200') {
        this.$message.success('上传成功!');
        let temp = [];
        res.object.forEach((item, v) => {
          temp.push({
            name: v,
            url: item
          })
        });
        this.fileListResultImg = [...temp, ...this.fileListResultImg];
      }
    },
    handleChangeTimeUnit1(val) {
      switch (val) {
        case 1:
          this.reactionTimeList = 60;
          break
        case 2:
          this.reactionTimeList = 60;
          break
        case 3:
          this.reactionTimeList = 24;
          break
      }
    },
    handleChangeTimeUnit2(val) {
      switch (val) {
        case 1:
          this.detectionTimeList = 60;
          break
        case 2:
          this.detectionTimeList = 60;
          break
        case 3:
          this.detectionTimeList = 24;
          break
      }
    },

    // 获取设备列表
    getDeviceList() {
      this.post(this.api.cooperationHospital.getDeviceList, {
        pageIndex: 0,
        pageSize: 1000,
      }).then(res => {
        if (res.data.code === '200') {
          this.deviceList = res.data.object;
        }
      });
    },
    // 获取检测项目列表
    getCheckItemList() {
      this.post(this.api.cooperationHospital.getCheckItemList, {
        pageIndex: 0,
        pageSize: 1000,
        name: ''
      }).then(res => {
        if (res.data.code === '200') {
          this.checkItemList = res.data.object;
        }
      });
    },
    // 获取厂商列表
    getFactoryList() {
      this.post(this.api.factory.getFactoryList, {
        name: '',
        pageIndex: 0,
        pageSize: 1000
      }).then(res => {
        if (res.data.code === '200') {
          this.factoryList = res.data.object;
        }
      });
    },
    // 选择厂商
    handleManufacturer(val) {
      this.model.factoryId = val;
      this.getProductLicensePage();
    },
    // 查询生产许可证
    async getProductLicensePage() {
      const {data: res} = await this.post(this.api.testStrip.getProductLicensePage, {
        factoryId: this.model.factoryId,
        name: ''
      })
      if (res.code === '200') {
        this.licenseList = res.object;
      }
    },
    // 选择生产许可证
    handleProductLicensePage(val) {
      this.productLicenseId = val;
      this.getCertificatePage();
    },
    // 查询医疗器械注册证
    async getCertificatePage() {
      const {data: res} = await this.post(this.api.testStrip.getCertificatePage, {
        factoryId: this.model.factoryId,
        productLicenseId: this.model.productLicenseId,
        name: ''
      })
      if (res.code === '200') {
        this.certificateList = res.object;
      }
    },
    // 查询试纸类型
    getTestStripList() {
      this.post(this.api.cooperationHospital.getTestStripTypeList, {
        'pageIndex': 0,
        'pageSize': 40
      }).then(res => {
        if (res.data.object) {
          this.paperTypeList = res.data.object;
        }
      });
    },
    // 选择试纸类型
    handleTestStripType(val) {
      this.model.testStripTypeId = val;
    },
    // 选择检测项目
    handleDevice(val) {
      this.model.deviceId = val;
      let devObj = this.checkItemList.find(item => item.id === val);
      this.model.deviceName = devObj.name;
      if (this.model.testStripTypeId !== 4) {
        this.getGoodTypes();
      }
      this.getDetectionIndexReferencesByDeviceId();
    },
    // 查询检测设备
    async getGoodTypes() {
      const {data: res} = await this.post(this.api.testStrip.getGoodTypes, {
        deviceId: this.model.deviceId,
        factoryId: this.model.factoryId,
        testStripId: this.dialogData.info.id,
        goodsTypeIds: this.dialogData.info.testStripFactoryDto.goodsTypeIds
      })
      if (res.code === '200') {
        this.listData = res.object;
      }
    },
    // 选择设备
    changeRadio(item) {
      let obj = this.listData.find(v => v.goodsTypeIds === item);
      this.currProperty = this.model.property = obj.goodsProperty;
      this.model.goodsTypeIds = obj.goodsTypeIds;
      let arrSampleName = obj.sampleName.split(',');
      this.sampleList = arrSampleName.map((item, index) => ({id: index, name: item}));
    },
    // 定性试纸-选择使用方式
    changeRadioTitle(item) {
      this.currTitleType = item;
    },
    // 检测项ID查询指标
    async getDetectionIndexReferencesByDeviceId() {
      const {data: res} = await this.post(this.api.testStrip.getDetectionIndexReferencesByDeviceId, {
        deviceId: this.model.deviceId
      })
      if (res.code === '200') {
        this.testPaperList = res.object;
      }
    },

    // 判断指标code,自有设备 - 指标code提交字段为code,第三方设备 - 指标code提交字段为referenceCode
    isCodeType() {
      let configDialog = {
        id: null, // 检测项与检测指标关系ID
        testStripFactoryId: this.dialogData.info.testStripFactoryDto.id, // 试纸厂商ID
        deviceId: this.model.deviceId, // 检测项目ID
        referenceUnit: '', // 单位
        referenceId: '', // 指标ID
        sortNum: '', // 排序
        criterion: '', // 指标判断条件（JSON数组字符串）
        criterionList: []
      }
      if (this.model.testStripTypeId === 4) {
        this.model.deviceReferenceDtoList.push({
          code: '',
          ...configDialog
        })
      } else {
        if (this.currProperty === 1) {
          this.model.deviceReferenceDtoList.push({
            code: '',
            ...configDialog
          });
        }
        if (this.currProperty === 2) {
          this.model.deviceReferenceDtoList.push({
            referenceCode: '',
            ...configDialog
          });
        }
      }

    },
    // 动态添加行
    handleAdd(data, op) {
      switch (op) {
        case 1:
          data.push({result: '', content: ''});
          break;
        case 2:
          data.push({result: ''});
          break;
        case 3:
          let res = this.model.deviceReferenceDtoList;
          if (res.length > 0) {
            let item = res[res.length - 1];
            if (item.referenceId === '') {
              this.$message.error('请选择指标!');
              return;
            }
            if (this.model.testStripTypeId !== 4) {
              if (item.referenceCode === '') {
                this.$message.error('请输入指标code!');
                return;
              }
            }
            this.isCodeType();
          } else {
            this.isCodeType();
          }
          break;
      }
    },
    // 动态删除 结果释义
    handleDel(table, index) {
      table.splice(index, 1);
    },
    // 动态删除行
    handleDelete(table, index) {
      table.splice(index, 1);
    },
    // 编辑配置判断标准
    openConfig(row, index) {
      if (row.referenceId === '') {
        this.$message.error('请先选择指标!');
        return
      }
      this.currIndex = index;
      this.dataList = row.criterionList;
      if (this.model.testStripTypeId !== 4) {
        this.changeRadio(this.model.goodsTypeIds);
      }
      this.isConfigView = true;
      this.dataList.forEach(item => {
        let isList = item.sampleName instanceof Array
        if (!isList) {
          //sampleName返回的是字符串，需要转换成数组
          if (item.sampleName) {
            //不为空字符串
            item.sampleName = Array(item.sampleName)
          } else {
            //为空字符串
            item.sampleName = []
          }
        }
        item.valueListSex = [{
          value: 1,
          label: '男'
        },
          {
            value: 0,
            label: '女'
          }];
        item.valueListBloodSugar = [
          {
            value: 0,
            label: '凌晨'
          },
          {
            value: 2,
            label: '早餐后1H'
          },
          {
            value: 3,
            label: '早餐后2H'
          },
          {
            value: 4,
            label: '午餐前'
          },
          {
            value: 5,
            label: '午餐后1H'
          },
          {
            value: 6,
            label: '午餐后2H'
          },
          {
            value: 7,
            label: '晚餐前'
          },
          {
            value: 8,
            label: '晚餐后1H'
          },
          {
            value: 9,
            label: '晚餐后2H'
          },
          {
            value: 10,
            label: '睡前'
          },
          {
            value: 11,
            label: '空腹'
          },
          {
            value: 12,
            label: '餐后1小时'
          },
          {
            value: 13,
            label: '餐后2小时'
          },
          {
            value: 99,
            label: '随机血糖'
          }];
      })
    },
    // 保存配置指标判断标准列表
    saveItem(row, index) {
      this.isConfigView = false;
      this.model.deviceReferenceDtoList[index].criterion = JSON.stringify(row.map(v => v));
      this.dataList = row;
    },
    // 新增 判断标准
    addConfig(data) {
      let timestamp = new Date().getTime();
      data.push({
        id: timestamp,
        sampleName: '',
        result: '',
        leftValue: undefined,
        leftRelation: undefined,
        rightRelation: undefined,
        rightValue: undefined,
        type: undefined,
        typeValue: undefined,
        note: undefined,
        isShowSelect: true, // 控制性别下拉选项
        isShowSelect2: false, // 控制血糖下拉选项
        isShowInput: false, // 控制年龄输入
        age: 0,
        status:'',
        valueListSex: [{
          value: 1,
          label: '男'
        },
          {
            value: 0,
            label: '女'
          }],
        valueListBloodSugar: [{
          value: 0,
          label: '凌晨'
        },
          {
            value: 2,
            label: '早餐后1H'
          },
          {
            value: 3,
            label: '早餐后2H'
          },
          {
            value: 4,
            label: '午餐前'
          },
          {
            value: 5,
            label: '午餐后1H'
          },
          {
            value: 6,
            label: '午餐后2H'
          },
          {
            value: 7,
            label: '晚餐前'
          },
          {
            value: 8,
            label: '晚餐后1H'
          },
          {
            value: 9,
            label: '晚餐后2H'
          },
          {
            value: 10,
            label: '睡前'
          },
          {
            value: 11,
            label: '空腹'
          },
          {
            value: 12,
            label: '餐后1小时'
          },
          {
            value: 13,
            label: '餐后2小时'
          },
          {
            value: 99,
            label: '随机血糖'
          }]
      })
    },
    // 移除 判断标准
    removeConfig(data, i) {
      data.splice(i, 1);
    },
    // 条件选择
    changeValueList(val, index) {
      let list = this.dataList[index];
      if (val === 'sex') {
        list.valueListSex = [{
          value: 1,
          label: '男'
        },
          {
            value: 0,
            label: '女'
          }];
        list.isShowSelect = true; // 控制性别下拉选项
        list.isShowSelect2 = false; // 控制血糖下拉选项
        list.isShowInput = false; // 控制年龄输入
        list.valueListBloodSugar = [];
      } else if (val === 'age') {
        list.isShowSelect = false; // 控制性别下拉选项
        list.isShowSelect2 = false; // 控制血糖下拉选项
        list.isShowInput = true; // 控制年龄输入
        list.valueListSex = [];
        list.valueListBloodSugar = [];
      } else if (val === 'bloodSugar') {
        list.isShowSelect = false; // 控制性别下拉选项
        list.isShowSelect2 = true; // 控制血糖下拉选项
        list.isShowInput = false; // 控制年龄输入
        list.valueListBloodSugar = [{
          value: 0,
          label: '凌晨'
        },
          {
            value: 2,
            label: '早餐后1H'
          },
          {
            value: 3,
            label: '早餐后2H'
          },
          {
            value: 4,
            label: '午餐前'
          },
          {
            value: 5,
            label: '午餐后1H'
          },
          {
            value: 6,
            label: '午餐后2H'
          },
          {
            value: 7,
            label: '晚餐前'
          },
          {
            value: 8,
            label: '晚餐后1H'
          },
          {
            value: 9,
            label: '晚餐后2H'
          },
          {
            value: 10,
            label: '睡前'
          },
          {
            value: 11,
            label: '空腹'
          },
          {
            value: 12,
            label: '餐后1小时'
          },
          {
            value: 13,
            label: '餐后2小时'
          },
          {
            value: 99,
            label: '随机血糖'
          }];
        list.valueListSex = [];
      }
    },
    // 选择指标,根据选择的指标回显 指标code
    chagneReference(val, index) {
      let obj = this.model.deviceReferenceDtoList.find(item => item.referenceId === val);
      let lists = this.model.deviceReferenceDtoList;
      if (this.model.testStripTypeId === 4) {
        lists[index].code = obj.code;
      } else {
        if (this.currProperty === 1) {
          lists[index].code = obj.code;
        }
        if (this.currProperty === 2) {
          lists[index].referenceCode = obj.referenceCode;
        }
      }
    },
    // 保存提交数据
    submitForm() {
      // 说明:定性试纸是没有样本的,样本是跟随设备走的,有设备,则可给设备配置样本
      this.$refs.formRef.validate((valid) => {
        if (valid) {

          // 定性试纸-试纸功效 2
          if (this.model.testStripTypeId === 4) {
            this.model.efficacy = 2;
            if (this.currTitleType === 2) {
              let map = new Map();
              Object.values(this.resultParaphraseTableData).forEach(item => {
                map.set(item.result, item.content);
              })
              let obj = {};
              map.forEach((item, index) => {
                obj[index] = item;
              })
              this.model.resultParaphrase = JSON.stringify(obj);
            }
            if (this.currTitleType === 3) {
              let resultsArray = [];
              this.resultTableData.map(v => {
                if (v.result.trim() !== '') {
                  resultsArray.push(v.result);
                }
              });
              this.model.results = resultsArray.length > 0 ? JSON.stringify(resultsArray) : null;
            }
            let fileListImg = this.fileListImg ? this.fileListImg.map(item => item.url) : [];
            this.model.useImageUrl = JSON.stringify(fileListImg);
            let fileListResultImg = this.fileListResultImg ? this.fileListResultImg.map(item => item.url) : [];
            this.model.resultImageUrl = JSON.stringify(fileListResultImg);

            // return
            this.post(this.api.cooperationHospital.saveTestStripFactory, this.model).then(({data}) => {
              if (data.code === '200') {
                this.$message.success('保存成功');
                this.$emit('closedialog');
              }
            })
          } else {
            let res = this.model.deviceReferenceDtoList;
            if (res.length > 0) {
              let item = res[res.length - 1];
              if (item.referenceId === '') {
                this.$message.error('请选择指标!');
                return;
              }
              // 判断数组里是否有相同的元素，size 属性返回当前 Set 元素总数
              let getReferenceId = res.map(item => item.referenceId);
              if (new Set(getReferenceId).size !== getReferenceId.length) {
                this.$message.error('不能配置相同的指标!');
                return
              }
              if (item.referenceCode === '') {
                this.$message.error('请输入指标code!');
                return;
              }
            }
            if (this.currProperty === 1) {
              this.post(this.api.cooperationHospital.saveTestStripFactory, this.model).then(({data}) => {
                if (data.code === '200') {
                  this.$message.success('保存成功');
                  this.$parent.initTableData();
                  this.$emit('closedialog');
                }
              })
            }
            if (this.currProperty === 2) {
              let dtosObj = this.deviceGoodsTypeDtos;
              let params = {
                goodsTypeIds: dtosObj.goodsTypeIds,
                property: dtosObj.goodsProperty
              }
              this.post(this.api.cooperationHospital.saveTestStripFactory, {
                ...params,
                ...this.model
              }).then(({data}) => {
                if (data.code === '200') {
                  this.$message.success('保存成功');
                  this.$parent.initTableData();
                  this.$emit('closedialog');
                }
              })
            }
          }
        }
      })
    },
  },
  created() {
    this.getDeviceList(); // 获取设备列表
    this.getFactoryList(); // 获取厂商列表
    this.getTestStripList();  // 查询试纸类型
    this.getCheckItemList(); // 获取检测项目列表
    if (this.dialogData.info) { // 详情
      this.post(this.api.cooperationHospital.getTestStripDetail, {
        id: this.dialogData.info.testStripFactoryDto.id
      }).then(res => {
        if (res.data.code === '200') {
          let resData = res.data.object;
          this.model = resData;
          // 回显 指标
          if (resData.deviceId) {
            if (this.model.testStripTypeId !== 4) {
              this.getGoodTypes();
            }
            this.getDetectionIndexReferencesByDeviceId();
          }
          if (resData.deviceReferenceDtoList) {
            this.model.deviceReferenceDtoList = resData.deviceReferenceDtoList;
          } else {
            this.$set(this.model, 'deviceReferenceDtoList', []);
          }
          if (this.model.deviceReferenceDtoList.length > 0) {
            this.model.deviceReferenceDtoList.forEach(item => {
              item.criterion = item.criterion ? item.criterion : '';
              item.criterionList = item.criterionList ? item.criterionList : [];
              item.criterionList.map((v, index) => {
                v.sampleName = v.sampleName && v.sampleName.length > 0 ? v.sampleName : '';
                if (!v.type) v.type == '';
                // if (!v.typeValue) v.typeValue;
                if (v.type === 'age') {
                  v.isShowSelect = false; // 控制性别下拉选项
                  v.isShowSelect2 = false; // 控制血糖下拉选项
                  v.isShowInput = true; // 控制年龄输入
                }
                if (v.type === 'sex') {
                  v.isShowSelect = true; // 控制性别下拉选项
                  v.isShowSelect2 = false; // 控制血糖下拉选项
                  v.isShowInput = false; // 控制年龄输入

                }
                if (v.type === 'bloodSugar') {
                  v.isShowSelect = false; // 控制性别下拉选项
                  v.isShowSelect2 = true; // 控制血糖下拉选项
                  v.isShowInput = false; // 控制年龄输入
                }
              })
            });
          }
          this.handleChangeTimeUnit1(resData.responseTimeUnit); // 反应时间
          this.handleChangeTimeUnit2(resData.checkTimeUnit); // 有效检测时间
          // 定性试纸 - 回显结果判读, 手动输入结果
          if (this.model.testStripTypeId === 4) {
            // 回显结果判读内容
            if (resData.resultParaphrase) {
              this.resultParaphraseTableData = [];
              let resObj = JSON.parse(resData.resultParaphrase);
              for (let k of Object.keys(resObj)) {
                this.resultParaphraseTableData.push({
                  result: k,
                  content: resObj[k]
                })
              }
            }
            this.currTitleType = 1;
            // 回显手动输入结果内容
            this.resultTableData = resData.results ? JSON.parse(resData.results).map(item => ({result: item})) : [];
            let res1 = JSON.parse(resData.useImageUrl);
            let res2 = JSON.parse(resData.resultImageUrl);
            this.fileListImg = res1.length > 0 ? res1.map((item, v) => ({
              name: v,
              url: item
            })) : [];
            this.fileListResultImg = res2.length > 0 ? res2.map((item, v) => ({
              name: v,
              url: item
            })) : [];
          } else {
            // 自有设备
            this.currProperty = this.model.property;
          }
          this.getProductLicensePage();
          this.getCertificatePage();
          this.model.efficacy = 1;

        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-upload-list--picture-card .el-upload-list__item {
  width: 98px !important;
  height: 98px !important;
}

.el-upload--picture-card {
  width: 98px !important;
  height: 98px !important;
  line-height: 98px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 98px !important;
  height: 98px !important;
  display: block;
}

.row-item {
  display: flex;
  justify-content: space-between;

  /deep/ .el-form-item {
    width: 100%;
  }

  /deep/ .el-form-item__content {
    width: 88%;
  }
}
</style>
